// const htmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const CopyPlugin = require('copy-webpack-plugin');
// 引入css拆分css plugin
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

// 打包前清空dist目录插件
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
	mode: 'development',
	entry: {
		index: './src/index.js',
		login: './src/login.js',
	},
	output: {
		filename: 'js/[name].js',
		path: path.resolve(__dirname, './dist'),
	},
	optimization: {
		minimize: true, // 代码压缩
		minimizer: [new UglifyJsPlugin(), new CssMinimizerPlugin()],
		splitChunks: {
			minSize: 3 * 1024,
			chunks: 'all',
			name: 'common',
			automaticNameDelimiter: '_',
			cacheGroups: {
				jquery: {
					name: 'jquery',
					chunks: 'all',
					test: /jquery\.js/,
				},
				lodash: {
					name: 'lodash',
					chunks: 'all',
					test: /lodash/,
				},
			},
		},
	},
	plugins: [
		new HtmlWebpackPlugin({
			filename: 'index.html',
			template: './src/index.html',
			chunks: ['index'],
		}),
		new HtmlWebpackPlugin({
			filename: 'login.html',
			template: './src/login.html',
			chunks: ['login'],
		}),
		new webpack.ProvidePlugin({
			$: 'jquery',
			jQuery: 'jquery',
		}),
		new CopyPlugin({
			patterns: [
				{
					from: path.resolve(__dirname, './src/img'),
					to: path.resolve(__dirname, './dist/img'),
				},
			],
		}),
		// 设置css plugin
		new MiniCssExtractPlugin({
			filename: 'css/[name].css',
			chunkFilename: 'css/[name].chunk.css',
		}),
		new CleanWebpackPlugin(),
	],
	module: {
		rules: [
			{
				test: /\.css$/i,
				use: [MiniCssExtractPlugin.loader, 'css-loader'],
			},
			// 通过asset模块，设置图片输出目录和判别大小
			{
				test: /\.(png|jpg|svg|jpeg|gif)$/i,
				type: 'asset',
				parser: {
					// 设置图片大小，如果超出8kb输出，小于则直接作为base64注入保重
					dataUrlCondition: {
						maxSize: 8 * 1024,
					},
				},
				// 输出目录
				generator: {
					filename: 'img/[name].[hash:6][ext]',
				},
			},
		],
	},
	devServer: {
		static: {
			directory: path.resolve(__dirname, '../dist'),
		},
		compress: true,
		port: 8000,
		hot: true,
	},
};
